#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
void RunChild()
{
    int cnt=5;
    while(cnt)
    {
        printf("i am child process\n");
        sleep(1);
        cnt--;
    }
}
int main()
{
    printf("This is process!\n");
    pid_t id = fork();
    if(id==0)//子进程
    {
        RunChild();
        exit(123);//子进程异常退出，退出码为123
    }
    sleep(1);

    while(1)
    {
        int status=0;
        pid_t rid=waitpid(id,&status,0);
        if(rid<0)//等待失败
        {
            printf("wait fail!\n");
            sleep(1);
            break;
        }
        else if(rid==0)//子进程未结束
        {
            printf("child is running,check next time!\n");
            sleep(1);
        }
        else//等待成功（程序运行结束）
        {
            if(WIFEXITED(status))//子进程正常退出
            {
                printf("child exit success!exit code:%d\n",WEXITSTATUS(status));
                sleep(1);
            }
            else//异常退出
            {
                printf("child exit fail\n");
                sleep(1);
            }
            break;
        }
    }
    return 0;
}
